
package jh.com.jhappbf.usermanager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.configs.Constant;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.UserModel;
import jh.com.jhappbf.security.DES;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.weight.query.SelectActivity;

/**
 * @author Administrator
 */
public class UserAdd extends AbActivity implements OnClickListener {

    private EditText mInputAccount;
    private EditText mInputName;
    private EditText mInputPwd;
    private EditText mInputConfirm;
    private EditText mTxtCompany;

    private ImageView mImgAccountClear;
    private ImageView mImgNameClear;
    private ImageView mImgPwdClear;
    private ImageView mImgConfirmClear;

    private RadioButton mRadNormal;
    private RadioButton mRadManager;

    private List<String> mData;
    private Map<String, String> mRight;
    private List<String> mSelectRight;
    private MyBaseAdapter mAdapter;
    private Boolean mIsAdd = false;
    private String mFlag = "";
    private static final int GETCOMPANY = 0x0001;
    private ImageView mImgCompany;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.user_add_activity);
        initView();
    }

    private void initView() {
        AbTitleBar mAbTitleBar = getTitleBar();
        mAbTitleBar.setTitleText("用户管理");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);

        mAbTitleBar.setLogoOnClickListener(v -> setResult());

        View rightViewMore = mInflater.inflate(R.layout.title_right_ok_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        Button mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_ok_btn);
        mTitleRightBtn.setOnClickListener(this);
        mInputAccount = findViewById(R.id.user_account_edit);
        mInputName = findViewById(R.id.user_name_edit);
        mInputPwd = findViewById(R.id.user_pwd_edit);
        mInputConfirm = findViewById(R.id.user_confirm_edit);
        mTxtCompany = findViewById(R.id.user_company_txt);
        mImgCompany = findViewById(R.id.user_company_select);
//        mTxtCompany.setOnClickListener(this);
        mImgCompany.setOnClickListener(this);

        mImgAccountClear = findViewById(R.id.user_account_clear);
        mImgNameClear = findViewById(R.id.user_name_clear);
        mImgPwdClear = findViewById(R.id.user_pwd_clear);
        mImgConfirmClear = findViewById(R.id.user_confirm_clear);

        mRight = new LinkedHashMap<>();
        mData = new ArrayList<>();
        mSelectRight = new ArrayList<>();

        mRight.put("查询管理", "weight");
//		mRight.put("计划管理", "plan");
        mRight.put("汇总管理", "collect");
        mRight.put("交货单确认", "saleOrder");
        mRight.put("采购单确认", "buyOrder");
//        mRight.put("预留单确认", "spareOrder");

//        mRight.put("确认装卸货", "load");
//        mRight.put("销售确认", "unload");
//        mRight.put("派车管理", "dispatch");
//        mRight.put("磅单管理", "receipt");
//		mRight.put("审核管理", "verify");
//        mRight.put("化验管理", "assay");
//        mRight.put("财务管理", "finance");
        mRight.put("用户管理", "manager");
 //       mRight.put("管理员", "admin");

        for (Entry<String, String> entry : mRight.entrySet()) {
            mData.add(entry.getKey());
        }
        ListView mList = findViewById(R.id.user_list_view);
        mAdapter = new MyBaseAdapter();
        mList.setAdapter(mAdapter);

        mImgAccountClear.setOnClickListener(this);
        mImgNameClear.setOnClickListener(this);
        mImgPwdClear.setOnClickListener(this);
        mImgConfirmClear.setOnClickListener(this);

        mRadNormal = findViewById(R.id.user_role_Normal);
        mRadManager = findViewById(R.id.user_role_manager);
        setUserInfo();
//        if ("/".equals(State.mCompanyName)) {
//            mTxtCompany.setOnClickListener(this);
//            mRadManager.setVisibility(View.VISIBLE);
//        } else {
//            mTxtCompany.setText(State.mCompanyName);
//            mRadManager.setVisibility(View.GONE);
//            mRadNormal.setChecked(true);
//        }

        mInputAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mImgAccountClear.setVisibility(View.GONE);
                } else {
                    mImgAccountClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mInputName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mImgNameClear.setVisibility(View.GONE);
                } else {
                    mImgNameClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mInputPwd.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mImgPwdClear.setVisibility(View.GONE);
                } else {
                    mImgPwdClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mInputConfirm.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mImgConfirmClear.setVisibility(View.GONE);
                } else {
                    mImgConfirmClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mList.setOnItemClickListener((parent, view, position, id) -> {
            CheckBox chk = view.findViewById(R.id.list_view_item_checkbox_textView_chk);
            String right = String.valueOf(chk.getTag());
            if (chk.isChecked()) {
                chk.setChecked(false);
                mSelectRight.remove(right);
            } else {
                chk.setChecked(true);
                if (!mSelectRight.contains(right)) {
                    mSelectRight.add(right);
                }
            }
        });
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo() {
        Intent i = getIntent();
        mFlag = i.getStringExtra("flag");
        if ("update".equals(mFlag)) {
            mInputAccount.setEnabled(false);
        } else {
            mInputAccount.setEnabled(true);
        }

        UserModel model = i.getParcelableExtra("user");
        if (model != null) {
            mInputAccount.setText(model.getAccount());
            mInputName.setText(model.getName());
            String pwd = DES.decrypt(model.getPwd(), Constant.DESKEY);
            mInputPwd.setText(pwd);
            mInputConfirm.setText(pwd);
            String company = model.getCompany();
            mTxtCompany.setText(company);

            String mRightStr = model.getRight();
            if (!TextUtils.isEmpty(mRightStr)) {
                String[] arr = mRightStr.split(":");
                for (String item : arr) {
                    if (item.length() > 0 && !mSelectRight.contains(item)) {
                        mSelectRight.add(item);
                    }
                }
            }
        }
    }

    /**
     * 设置返回状态
     */
    private void setResult() {
        Intent i = new Intent();
        i.putExtra("result", mIsAdd);
        setResult(RESULT_OK, i);
        UserAdd.this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_account_clear:
                mInputAccount.setText("");
                break;
            case R.id.user_name_clear:
                mInputName.setText("");
                break;
            case R.id.user_pwd_clear:
                mInputPwd.setText("");
                break;
            case R.id.user_confirm_clear:
                mInputConfirm.setText("");
                break;
            case R.id.user_company_txt:
            case R.id.user_company_select:
                Intent intent = new Intent(UserAdd.this, SelectActivity.class);
                intent.putExtra("flag", "receiver");
                startActivityForResult(intent, GETCOMPANY);
                break;
            case R.id.title_right_ok_btn:
                operateServer();
                break;
            default:
                break;
        }
    }

    private void operateServer() {
        AbLoadDialogFragment mDialogFragment = AbDialogUtil.showLoadDialog(UserAdd.this,
                R.mipmap.ic_load, "操作中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::addUser);
    }

    private void addUser() {
        String account = mInputAccount.getText().toString();
        String name = mInputName.getText().toString();
        String pwd = mInputPwd.getText().toString();
        String confirm = mInputConfirm.getText().toString();
        String company = mTxtCompany.getText().toString();
        if (account.length() == 0) {
            AbDialogUtil.removeDialog(UserAdd.this);
            Toast.makeText(UserAdd.this, "账号不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (name.length() == 0) {
            AbDialogUtil.removeDialog(UserAdd.this);
            Toast.makeText(UserAdd.this, "用户名称不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (pwd.length() == 0) {
            AbDialogUtil.removeDialog(UserAdd.this);
            Toast.makeText(UserAdd.this, "密码不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!pwd.equals(confirm)) {
            AbDialogUtil.removeDialog(UserAdd.this);
            Toast.makeText(UserAdd.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        pwd = DES.encrypt(pwd, Constant.DESKEY);
        StringBuilder rightBuilder = new StringBuilder();
        for (String item : mSelectRight) {
            if (item.length() > 0) {
                rightBuilder.append(item).append(":");
            }
        }

//		if (company.length() == 0 && mRadNormal.isChecked()) {
//			AbDialogUtil.removeDialog(UserAdd.this);
//			Toast.makeText(UserAdd.this, "公司名称不能为空!", Toast.LENGTH_SHORT)
//					.show();
//			return;
//		}

        String methodName = "addUser";
        if ("update".equals(mFlag)) {
            methodName = "updateUserInfo";
        }
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("account");
        param.add("userName");
        param.add("pwd");
        param.add("right");
        param.add("company");
        param.add("pid");
        value.add(account);
        value.add(name);
        value.add(pwd);
        value.add(rightBuilder.toString());
        value.add(company);
        value.add(State.mAccount);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UserAdd.this);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null && data.size() > 0) {
                JSONObject obj = data.get(0);
                if (obj != null) {
                    String memo = obj.optString("memo");
                    String result = obj.optString("result");
                    if ("true".equals(result)) {
                        mIsAdd = true;
                        if ("add".equals(mFlag)) {
                            refresh();
                        } else {
                            setResult();
                        }
                    }
                    Toast.makeText(UserAdd.this, memo, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UserAdd.this, "操作失败!", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(UserAdd.this, "操作失败!", Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UserAdd.this);
            Toast.makeText(UserAdd.this, "网络不给力,请重试!", Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService httpService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton volley = VolleySingleton.getVolleyInstance(getApplicationContext());
        volley.addRequest(httpService);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String result = data.getStringExtra("result");
            mTxtCompany.setText(result);
            mInputName.setText(result);
            mInputAccount.setText(result);
        }
    }

    /**
     * 刷新
     */
    private void refresh() {
        mInputAccount.setText("");
        mInputName.setText("");
        mInputPwd.setText("");
        mInputConfirm.setText("");
        mTxtCompany.setText("");
        mSelectRight.clear();
        mAdapter.notifyDataSetChanged();
    }

    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_view_item_checkbox_textview, null);
                holder = new ViewHolder();
                holder.mTxt = convertView.findViewById(R.id.list_view_item_checkbox_textView_txt);
                holder.mChk = convertView.findViewById(R.id.list_view_item_checkbox_textView_chk);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String rightName = mData.get(position);
            holder.mTxt.setText(rightName);
            if (mRight.keySet().contains(rightName)) {
                String right = mRight.get(rightName);
                holder.mChk.setTag(right);
                if (mSelectRight.contains(right)) {
                    holder.mChk.setChecked(true);
                } else {
                    holder.mChk.setChecked(false);
                    mSelectRight.remove(right);
                }
            }
            return convertView;
        }
    }

    class ViewHolder {
        TextView mTxt;
        CheckBox mChk;
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
